{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Parameter Histograms\n",
    "\n",
    "This notebook loads a model and draws the histograms of the parameters tensors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import scipy.stats as ss\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import distiller\n",
    "import distiller.models as models\n",
    "\n",
    "plt.style.use('seaborn') # pretty matplotlib plots"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load your model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# It is interesting to compare the distribution of non-pretrained model (Normally-distributed)\n",
    "# vs. the distribution of the pretrained model.\n",
    "model = models.create_model(pretrained=True, dataset='imagenet', arch='resnet50',\n",
    "                            device_ids=-1)  # load to CPU\n",
    "\n",
    "# Optionally load your compressed model \n",
    "# distiller.apputils.load_checkpoint(model, <path-to-your-checkpoint-file>)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot the distributions\n",
    "\n",
    "We plot the distributions of the weights of each convolution layer, and we also plot the fitted Gaussian and Laplacian distributions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "def getSparsity(x):\n",
    "    return 1 - (x[x.nonzero()].size / x.size)\n",
    "\n",
    "REMOVE_ZEROS = False\n",
    "nbins = 500\n",
    "for name, weights in model.named_parameters():\n",
    "    if weights.dim() != 4:\n",
    "        # not convolution layer\n",
    "        continue\n",
    "\n",
    "    shape_str = \"x\".join(map(str, weights.shape))\n",
    "    weights = weights.cpu().detach().numpy().flatten()\n",
    "    sparsity = getSparsity(weights)\n",
    "\n",
    "    if REMOVE_ZEROS:\n",
    "        # Optionally remove zeros (lots of zeros will dominate the histogram and the \n",
    "        # other data will be hard to see\n",
    "        weights = weights[weights.nonzero()]\n",
    "\n",
    "    # Fit the data to the Normal distribution\n",
    "    (mean_fitted, std_fitted) = ss.norm.fit(weights)\n",
    "    x = np.linspace(min(weights), max(weights), nbins)\n",
    "    weights_gauss_fitted = ss.norm.pdf(x, loc=mean_fitted, scale=std_fitted)\n",
    "\n",
    "    # Fit the data to the Laplacian distribution\n",
    "    (mean_fitted, std_fitted) = ss.laplace.fit(weights)\n",
    "    weights_laplace_fitted = ss.laplace.pdf(x, loc=mean_fitted, scale=std_fitted)\n",
    "\n",
    "    n, bins, patches = plt.hist(weights, histtype='stepfilled', \n",
    "                                cumulative=False, bins=nbins, density=True)\n",
    "    plt.plot(x, weights_gauss_fitted, label='gauss')\n",
    "    plt.plot(x, weights_laplace_fitted, label='laplace')\n",
    "\n",
    "    plt.title(name + \" - \" + shape_str + (\n",
    "        ' - sparsity: {:.0%}'.format(sparsity) if REMOVE_ZEROS else ''))\n",
    "    #plt.figure(figsize=(10,5))\n",
    "    plt.legend()\n",
    "    plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
